'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'

export default function DebugFieldNamesPage() {
  const [fieldData, setFieldData] = useState<any>(null)
  const [userInfo, setUserInfo] = useState<any>(null)
  const [permissionInfo, setPermissionInfo] = useState<any>(null)
  const [loading, setLoading] = useState(false)

  const checkFieldData = async () => {
    setLoading(true)
    try {
      // 1. 检查字段元数据
      const fieldResponse = await fetch('/api/field-metadata?tableName=table_c2')
      const fieldData = await fieldResponse.json()
      console.log('字段元数据:', fieldData)

      // 2. 检查用户信息
      const userResponse = await fetch('/api/auth/me')
      const userData = await userResponse.json()
      console.log('用户信息:', userData)

      // 3. 检查权限信息
      const permResponse = await fetch('/api/auth/permissions?tableName=table_c2')
      const permData = await permResponse.json()
      console.log('权限信息:', permData)

      // 4. 检查设备参数
      const paramResponse = await fetch('/api/device-parameters?deviceId=1&tableName=table_c2')
      const paramData = await paramResponse.json()
      console.log('设备参数:', paramData)

      setFieldData(fieldData)
      setUserInfo(userData)
      setPermissionInfo(permData)

    } catch (error) {
      console.error('检查失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const testLogin = async () => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          username: 'design', 
          password: 'design123' 
        }),
      })

      const data = await response.json()
      console.log('登录响应:', data)
      
      // 登录后立即检查数据
      setTimeout(checkFieldData, 1000)
    } catch (error) {
      console.error('登录失败:', error)
    }
  }

  useEffect(() => {
    checkFieldData()
  }, [])

  return (
    <div className="p-8 space-y-6">
      <h1 className="text-2xl font-bold">字段名和权限调试</h1>
      
      <div className="flex space-x-4">
        <Button onClick={checkFieldData} disabled={loading}>
          {loading ? '检查中...' : '检查数据'}
        </Button>
        <Button onClick={testLogin} variant="outline">
          测试登录 (design)
        </Button>
      </div>

      {fieldData && (
        <Card>
          <CardHeader>
            <CardTitle>字段元数据 (table_c2)</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <h4 className="font-medium">字段列表:</h4>
              {fieldData.data?.fields?.map((field: any, index: number) => (
                <div key={index} className="text-sm border-l-2 border-gray-200 pl-3">
                  <div><strong>字段名:</strong> "{field.field_name}"</div>
                  <div><strong>数据来源:</strong> {field.data_source}</div>
                  <div><strong>序号:</strong> {field.field_sequence}</div>
                  <div><strong>是否必填:</strong> {field.is_required ? '是' : '否'}</div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {userInfo && (
        <Card>
          <CardHeader>
            <CardTitle>用户信息</CardTitle>
          </CardHeader>
          <CardContent>
            <pre className="text-xs bg-gray-100 p-2 rounded overflow-auto">
              {JSON.stringify(userInfo, null, 2)}
            </pre>
          </CardContent>
        </Card>
      )}

      {permissionInfo && (
        <Card>
          <CardHeader>
            <CardTitle>权限信息</CardTitle>
          </CardHeader>
          <CardContent>
            <pre className="text-xs bg-gray-100 p-2 rounded overflow-auto">
              {JSON.stringify(permissionInfo, null, 2)}
            </pre>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
